<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\Packets;

use Kcdns\Admin\Controller\PublicController;
class Packets extends \Service\Common\BaseModel
{
    protected $name = 'red_packets';

    

    //红包列表
    public function  packets($uid, $page_num = 1, $page_size = 5){
    	$where = [
    	    'uid'=>$uid,
    	    'type'=>0
    	   ];
    	$list = (array)$this->where($where)
    	                    ->order('id desc')
    	                    ->page($page_num, $page_size)
    	                    ->select();
    	$page_count = $this->where($where)->count();
    	$page_total = ceil($page_count / $page_size);
    	return [
    	$list,
    	$page_count,
    	$page_total
    	];
    }
    
  
    //发红包
    public function packetsout($uid)
    {
        
    	$packets_start_time = date('Y-m-d').' '.C('packets_start_time',null,'17:00:00')?:'17:00:00';
    	$packets_end_time = date('Y-m-d').' '.C('packets_end_time',null,'23:59:59')?:'23:59:59';
    	$time = date('Y-m-d H:i:s');
    	if (!(strtotime($time) >= strtotime($packets_start_time) && 
    		  strtotime($time) <= strtotime($packets_end_time))) {
    		throw new \Exception('当前时间无法领取红包');
    	}
    	$packets_total_rate = C('packets_total_rate',null,0.02)?:0.02;//红包总比率
    	$packets1_quota = C('packets1_quota',null,0);//红包一档额度
    	$packets1_odds = C('packets1_odds',null,0);//红包一档获得几率
    	$packets2_quota = C('packets2_quota',null,0);//红包二档额度
    	$packets2_odds = C('packets2_odds',null,0);//红包二档获得几率
    	$packets3_quota = C('packets3_quota',null,0);//红包三档额度
    	$packets3_odds = C('packets3_odds',null,0);//红包三档获得几率
    	$packets4_quota = C('packets4_quota',null,0);//红包四档额度
    	$packets4_odds = C('packets4_odds',null,0);//红包四档获得几率
    	$packets5_quota = C('packets5_quota',null,0);//红包五档额度
    	$packets5_odds = C('packets5_odds',null,0);//红包五档获得几率
    	$proArr =[
	    	$packets5_quota => $packets5_odds,
	    	$packets4_quota => $packets4_odds,
	    	$packets3_quota => $packets3_odds,
	    	$packets2_quota => $packets2_odds,
	    	$packets1_quota => $packets1_odds,
    	];
    	foreach ($proArr as $k=>$v){
    		if ($k <= 0 || $v <= 0) {
    			unset($proArr[$k]);
    		}
    	}
    	
    	$result = $this->table('__UCENTER_MEMBER__ a')
				    	->where(['a.id'=>$uid,
				    			'b.vip_level'=>['in',C('packets_level',null,'1,2,3')],
				    			])
				    	->join('__USER__ b on b.uid = a.id')
				    	->find();
    	if (!$result) {
    		throw new \Exception("抱歉，您不符合领取红包级别");
    	}
    	$date = date('Y-m-d',strtotime("-1 day"));
    	$num = 0;
    
    	 $count = $this->where([
    			       'uid'=>$uid,
    			       'create_time'=>[
    			           ['egt', date('Y-m-d 00:00:00')],
    			           ['elt', date('Y-m-d 23:59:59')],
    			        ]
    			])->count();
    	if ($count > $num) {
    		throw new \Exception("您今天已经领取了红包，无法重复领取");
    	} 
    	
    	$day_order_quota = $this->getOrderQuota($date , $date);//昨日订单总额
    	$total_red_packets_quota = number_format(
							    	$day_order_quota * $packets_total_rate,
							    	2,
							    	'.',
							    	''
							    			);//今日产生红包总额
    	
    	if ($total_red_packets_quota <= 0) {
    		throw new \Exception("抱歉，今日没有产生红包");
    	}
    	$day_total_packets_quota = $this->getTotalPacketsQuota('',date('Y-m-d') , date('Y-m-d'),0);//今日发出红包总额
    	$packets_quota = $total_red_packets_quota - $day_total_packets_quota;//剩余红包额度
    	$packets = $this->getRedPackets($proArr,$packets_quota);//红包金额
        $update = M('user')->where(['uid'=>$uid])
                           ->save([
        		              'red_packets'=> ['exp','red_packets+'.$packets],
        		              'total_red_packets'=>['exp','total_red_packets+'.$packets]
        		                   ]);
        if ($update === false) {
        	throw new \Exception("红包领取失败");
        }
        
        $packetsid = $this->add([
        		          'uid'=>$uid,
        		          'type'=>0,
        		          'money'=>$packets,
        		          'create_time'=>date('Y-m-d H:i:s')
        		      ]);
        if (!$packetsid) {
        	throw new \Exception("红包记录添加失败");
        }
       
        return $packets;
    
    }
    
    
    public function getTotalPacketsQuota($uid = '',$start_time = '' , $end_time = '',$type='')
    {
    	$where = [];
    	if ($type !== '') {
    		$where['type'] =  $type;
    	}
    	
    	if ($uid) {
    		$where['uid'] = $uid;
    	}
    	if ($start_time || $end_time) {
    		if ($start_time) {
    			$where['create_time'][] = ['egt', $start_time . ' 00:00:00'];
    		}
    		if ($end_time) {
    			$where['create_time'][] = ['elt', $end_time . '23:59:59'];
    		}
    	}
    
    	return number_format(
    			$this->where($where)->sum('money'),
    			2,
    			'.',
    			''
    	);
    }
    
    public function getOrderQuota($start_time = '' , $end_time = '')
    {
    	$where = [
           
            'pay_status' => 1
        ];
    	
        if ($start_time || $end_time) {
            if ($start_time) {
                $where['pay_time'][] = ['egt', $start_time . ' 00:00:00'];
            }
            if ($end_time) {
                $where['pay_time'][] = ['elt', $end_time . '23:59:59'];
            }
        }

        return number_format(
            M('order')->where($where)->sum('pay_money'),
            2,
            '.',
            ''
        );
    }
    
    
    Public function getRedPackets($proArr,$packets_quota)
    {
    	if ($packets_quota < min(array_flip($proArr))) {
    		 throw new \Exception("抱歉，今日红包已领完");
    	}
    	$packets = $this->get_rand($proArr);
    	if ($packets > $packets_quota) {
    		return $this->getRedPackets($proArr, $packets_quota);
    	}
    	return $packets;
    }

    public function get_rand($proArr) {
    	$result = '';
    	//概率数组的总概率精度
    	$proSum = array_sum($proArr);
    	//概率数组循环
    	foreach ($proArr as $key => $proCur) {
    		$randNum = mt_rand(1, $proSum);             //抽取随机数
    		if ($randNum <= $proCur) {
    			$result = $key;                         //得出结果
    			break;
    		} else {
    			$proSum -= $proCur;
    		}
    	}
    	unset ($proArr);
    	return $result;
    }
    
    
}